$(function () {
    resetui()
    $('#btnSend').on('click', function () {
        const content = $('#ipt').val().trim()
        if (content === '') {
            $('#ipt').val('')
            return alert('请输入内容')
        }
        $('#talk_list').append(`
            <li class="right_word">
                <img src="img/person02.png" /> <span>${content}</span>
            </li>
        `)
        resetui()
        $('#ipt').val('')
        getRobot(content)
    })
    $('#ipt').keydown(function (e) {
        if (e.key === 'Enter') {
            $('#btnSend').click()

        }
    })
    function getRobot(content) {
        console.log('用户说的话: ', content)
        $.ajax({
            method: 'GET',
            url: 'http://ajax-api.itheima.net/api/robot',
            data: {
                spoken: content,
            },
            success: function (res) {
                console.log(res)
                if (res.message !== 'success') return alert('获取失败')
                const text = res.data.info.text
                console.log('机器人说的话: ', text)
                $('#talk_list').append(`
                    <li class="left_word">
                        <img src="img/person01.png" /> <span>${text}</span>
                    </li>
                `)
                resetui()
                getVoice(text)
            },
        })
    }

    function getVoice(text) {
        $.ajax({
            method: 'GET',
            url: 'http://ajax-base-api-t.itheima.net/api/synthesize',
            data: {
                text,
            },
            success(res) {
                console.log(res)

                if (res.status !== 200) return alert('获取语音失败')
                $('#voice').attr('src', res.voiceUrl)
            },
        })
    }
})
